# -*- encoding: utf-8 -*-
import re
import json
import requests
import datetime
from bs4 import BeautifulSoup
from .result import result

CHECK_SSFW_URL = 'http://ssfw.hlju.edu.cn/ssfw/j_spring_ids_security_check'
EXAM_URL = 'http://ssfw.hlju.edu.cn/ssfw/xsks/kcxx.do'


def request_exams(uid,token):
    cookie = {'iPlanetDirectoryPro':token}

    data = None
    for i in range(10):
        print('request exam: ',i)
        if data != None:
            break
        try:
            session = requests.session()
            session.get(CHECK_SSFW_URL,cookies = cookie,timeout=2)
            req = session.get(EXAM_URL,cookies = cookie,timeout=2)

            # if int(req.headers.get('Content-Length')) < 14000:
            #     continue

            p = re.compile('</span>')
            html = p.sub('',req.text)

        except requests.Timeout as e:
            continue

        except requests.ConnectionError as e:
            return result(107)

        except Exception as e:
            print(e)
            return result(105)

        data = parse_exams(uid,html)

    # if there still have no data after 10 times tried, it means verify expired
    if data == None:
        return result(108)

    return result(100,sort_data(data))


def parse_exams(uid,html):
    trs = BeautifulSoup(html,'html.parser').find_all('tr',class_='t_con')
    if len(trs) == 0:
        return None

    json_list = []
    for tr in trs:
        item_list = tr.find_all('td')

        if len(item_list)<10:
            continue

        cid = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
        cn = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
        cp = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)
        teacher = '--' if len(item_list[4].get_text(strip = True)) == 0 else item_list[4].get_text(strip = True)
        credit = 0.0 if len(item_list[5].get_text(strip = True)) == 0 else float(item_list[5].get_text(strip = True))

        # print('exam time is: ',item_list[6].get_text(strip = True))

        examTimes = item_list[6].get_text(strip = True).split(' ')

        ed = "待定" if len(examTimes) < 2 else examTimes[0]
        et = "待定" if len(examTimes) < 2 else examTimes[1]

        # et = '--' if len(item_list[6].get_text(strip = True)) == 0 else item_list[6].get_text(strip = True)

        exam_loc = item_list[7].get_text(strip = True).split('-')
        if len(exam_loc) == 3:
        	el = exam_loc[1]+'-'+exam_loc[2]
        else:
        	el = '--'

        ety = '--' if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)
        em = '--' if len(item_list[9].get_text(strip = True)) == 0 else item_list[9].get_text(strip = True)
        es = '--' if len(item_list[10].get_text(strip = True)) == 0 else item_list[10].get_text(strip = True)

        json_list.append({'uid':uid,'cid':cid,'cname':cn,'property':cp,'teacher':teacher,
        'credit':credit,'date':ed,'time':et,'classroom':el,'type':ety,'method':em,'status':es})

    return json_list


# 将数据排序，排序规则是：考过的降序排最后，没考的升序排前面
def sort_data(data_list):
    closed = []  # 已结束
    nobegin = [] # 未开始
    almost = []  # 即将开始
    other = []   #其他

    for item in data_list:
        if item.get('status')=='已结束':
            closed.append(item)
        elif item.get('status')=='未开始':
            nobegin.append(item)
        elif item.get('status')=='--':
            end_time = item.get('time').split('-')[1]
            end_date = item.get('date')

            end_time = datetime.datetime.strptime(end_date+" "+end_time,'%Y-%m-%d %H:%M')
            now_time = datetime.datetime.now()
            if now_time > end_time:# 如果已经结束了
                item['status']='已结束'
            # 后续版本可以增加正在考试中的状态
            almost.append(item)
        else:
            other.append(item)

    if closed != None:
        closed.reverse()
    return almost + nobegin + closed + other


if __name__ == '__main__':

     data = request_exams('20135081','AQIC5wM2LY4SfcwQERBRJXh3RneLJh9R92VyA5HcNJqkTp4%3D%40AAJTSQACMDE%3D%23').encode('utf-8')
     print(data)
